#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pthread.h>

// 定义全局互斥锁
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;

void write_log(int line,const char *func,const char *format, ...) {
    pthread_mutex_lock(&log_mutex); // 加锁

    int fd = open("./client.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
    if (fd < 0) {
        printf("The log file failed to open\n");
        pthread_mutex_unlock(&log_mutex); // 失败时也要解锁
        return;
    }

    // 写入时间戳
    time_t t = time(NULL);
    struct tm *lt = localtime(&t);
    char time_buf[64];
    snprintf(time_buf, sizeof(time_buf), "[%04d-%02d-%02d %02d:%02d:%02d] ",
             lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
             lt->tm_hour, lt->tm_min, lt->tm_sec);

    // 写入日志内容的时间戳、行号、函数名
    dprintf(fd,"%s[Line %d] [Function: %s] ",time_buf,line,func);

    // 写入日志内容
    char msg_buf[1024];
    va_list args;
    va_start(args, format);
    vsnprintf(msg_buf, sizeof(msg_buf), format, args);
    va_end(args);
    
    // 写入日志信息
    dprintf(fd,"%s\n",msg_buf);

    close(fd);

    pthread_mutex_unlock(&log_mutex); // 解锁
}

